// pages/attractionsDetail/attractionsDetail.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    spotId:"",
    rank:"",
    images: [],
    attraction: {
      title: '',
      rating: "",
      reviewCount: "",
      latestEntryTime: '18:00',
      address: ''
    },
    guideItems: [],
    comboTickets:[],
    groupedTickets: [], // 分组后的门票数据
    reviews: []
  },
  onClickLeft(){
    wx.navigateBack();
  },
  onBookTap(e) {
    const ticketId = e.currentTarget.dataset.ticketId;
    console.log(ticketId)
    wx.navigateTo({
      url: `/pages/attractionsOrder/attractionsOrder?ticketId=${ticketId}&spotId=${this.data.spotId}`,
    });
  },

  getBannerImage() {
    const app = getApp();
    wx.request({
      url: 'http://localhost:8080/system/image/list',
      header: {
        Authorization: app.globalData.token
      },
      data: {
        aid: this.data.spotId // 使用当前景点 ID 查询对应的图片
      },
      success: (res) => {
        if (res.data.code === 200) {
          const baseUrl = 'http://localhost:8080';
  
          // 过滤出 state == 1 的图片，并拼接完整 URL
          const imageList = res.data.rows
            .filter(item => item.state === 1)
            .map(item => baseUrl + item.imgUrl);
  
          if (imageList.length > 0) {
            this.setData({
              images: imageList // 更新轮播图数据
            });
          } else {
            wx.showToast({ title: '暂无有效轮播图', icon: 'none' });
          }
        } else {
          wx.showToast({ title: '查询失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      }
    });
  },

  loadAttractions(Id){
    wx.request({
      url: `http://localhost:8080/system/spot/${Id}`,
      header: {
        Authorization: app.globalData.token
      },
      success: (res) => {
        if (res.data.code === 200) {
          const spot = res.data.data;
  
          // 构造 attraction 对象
          const attraction = {
            title: spot.name,
            rating: spot.star,
            reviewCount: spot.commentCount || 0,
            address: spot.address
          };
  
          // 更新页面数据
          this.setData({
            attraction: attraction
          });
        } else {
          wx.showToast({ title: '加载景点详情失败', icon: 'none' });
        }
      },
    })
  },

  stepIntroduce(){
      wx.navigateTo({
        url: `/pages/attractionsIntroduce/attractionsIntroduce?id=${this.data.spotId}`,
      })
  },

  getProject(){
    const baseUrl = 'http://localhost:8080';
    wx.request({
      url: 'http://localhost:8080/system/project/list',
      header: {
        Authorization: app.globalData.token
      },
      data:{aid:this.data.spotId},
      success: (res) => {
        console.log(res)
        if (res.data.code === 200) {
          // 处理数据：拼接图片 URL 并提取 title
          const projectList = res.data.rows.map(item => ({
            imageUrl: baseUrl + item.imgUrl,
            title: item.name
          }));
  
          // 更新 guideItems 数据
          this.setData({
            guideItems: projectList
          });
        } else {
          console.log('暂无项目信息');
        }
      },
      fail: () => {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      }
    })
  },

  getTicket(){
    wx.request({
      url: `http://localhost:8080/system/ticket/list`,
      header: {
        Authorization: app.globalData.token
      },
      data:{aid:this.data.spotId},
      success: (res) => {
        if (res.data.code === 200 && Array.isArray(res.data.rows)) {
          const tickets = res.data.rows;
  
          //分组
          const map = {};
          const result = [];
  
          tickets.forEach(ticket => {
            const key = ticket.name;
  
            if (!map[key]) {
              map[key] = {
                type: key,
                list: []
              };
              result.push(map[key]);
            }
  
            map[key].list.push({
              type: ticket.name,
              name: ticket.title,
              price: ticket.price,
              ticketId:ticket.id
            });
          });
  
          // 更新页面数据
          this.setData({
            groupedTickets: result
          });
          console.log("111",this.data.groupedTickets)
        } else {
          wx.showToast({ title: '暂无门票信息', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      }
    })
  },

  getComment() {
    const baseUrl = 'http://localhost:8080';
    wx.request({
      url: 'http://localhost:8080/system/comment/list',
      header: {
        Authorization: app.globalData.token
      },
      data: {
        aid: this.data.spotId
      },
      success: (res) => {
        if (res.data.code === 200 && Array.isArray(res.data.rows)) {
          const commentList = res.data.rows
            .filter(item => item.state === 1)
            .map(item => ({
              avatar: baseUrl + item.avatar,
              nickname: item.nickName,
              rating: item.star,
              content: item.content,
              date: item.time.split(' ')[0],
              imageList: item.imgUrl ? item.imgUrl.split(',').map(url => baseUrl + url) : []
            }));
  
          // 保存全部评论用于跳转页面使用
          this.setData({
            reviews: commentList.slice(0, 2), // 只显示前两条
            allReviews: commentList // 保存所有评论
          });
        } else {
          wx.showToast({ title: '暂无评论信息', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      }
    });
  }
  ,
  
  
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options && options.id) {
      const Id = options.id;
      const buyTicketRank = options.buyTicketRank;
      // console.log('接收到的景点ID:', Id);
      this.setData({
        spotId:Id,
        rank:buyTicketRank
      })
      // console.log('景点ID:', this.data.spotId);
      // console.log("paihang",this.data.rank)
      this.loadAttractions(Id);
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getBannerImage();
    this.getProject();
    this.getTicket();
    this.getComment();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})